


var mosca = require('mosca')

//ascoltatore是Mosca作者开发的一个订阅与发布类库，Mosca核心的订阅与发布模型
var ascoltatore = {
  type: 'redis',  //指定类型，mongo的写法请参考官方wiki
  redis: require('redis'),
  db: 1,  
  port: 6379,
  return_buffers: true, // to handle binary payloads
  //指定数据保留多长时间，单位毫秒
  ttl: {
    // TTL for subscriptions is 23 hour
    subscriptions: 23 * 60 * 60 * 1000,
    // TTL for packets is 23 hour
    packets: 23 * 60 * 60 * 1000,
  },
  host: "localhost"
};

//基本参数设置
var moscaSettings = {
  port: 1883, //设置监听端口
  backend: ascoltatore,
  maxInflightMessages: 10240, //设置单条消息的最大长度，超出后服务端会返回
  //设置WebSocket参数
  http: {
    port: 1884,
    bundle: true,
    static: './'
  },
  //数据持久化参数设置
  persistence: {
    factory: mosca.persistence.Redis,
    db: 1,
    port: 6379,
    return_buffers: true, // to handle binary payloads
    ttl: {
      // TTL for subscriptions is 23 hour
      subscriptions: 23 * 60 * 60 * 1000,
      // TTL for packets is 23 hour
      packets: 23 * 60 * 60 * 1000,
    },
    host: "localhost"
  }
};

//如果需要用户登录验证权限，需要改写此方法
//这里以简单判断了用户名和密码为例，真实环境可以连接实际业务系统的鉴权服务
var authenticate = function(client, username, password, callback) {
  var authorized = (username === 'test' && password.toString() === 'passwd');
  if (authorized) client.user = username;
  callback(null, authorized);
}

function authPub(client, topic, payload, callback) {
  callback(null, payload);
}

function authSub(client, topic, callback) {
  callback(null, topic);
}


var server = new mosca.Server(moscaSettings);

server.on('clientConnected', function(client) {
  console.log('client connected', client.id);
});

server.on('published', function(packet, client) {
  console.log('Published', packet.topic + packet.payload);
});

server.on('ready', setup);
// fired when the mqtt server is ready
function setup() {
  server.authenticate = authenticate;
  server.authorizePublish = authPub;
  server.authorizeSubscribe = authSub;

  console.log('Mosca server is up and running')
}
}